<?php


namespace App\Services\Company\Services;

use App\Services\Business\Models\Expiredables;

use App\Services\Company\Interfaces\CompanyRoleServiceInterface;
use App\Services\Member\Models\Role;
use App\Services\Member\Models\UserRole;
use App\Services\Company\Interfaces\CompanyServiceInterface;
use App\Services\Company\Models\CompanyJoinRoleRecord;
use App\Services\Company\Models\CompanyRole;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class CompanyRoleService implements CompanyRoleServiceInterface
{

    /**
     * @var CompanyService
     */
    protected $companyService;

    public function __construct(CompanyServiceInterface $companyService)
    {
        $this->companySerivice = $companyService;
    }

    public function all(): array
    {
        return Role::query()->with(['company', 'privileges'])->orderBy('weight')->get()->toArray();
    }


    /**
     * @param int $id
     * @return array
     */
    public function find(int $id)
    {
        return CompanyRole::query()->findOrFail($id)->toArray();
    }



    /**
     * @param int $id
     * @return Builder|Builder[]|Collection|Model|null
     */
    public function get(int $id)
    {
        return CompanyRole::query()->with(['privileges','expireds'])->find($id);

    }

    /**
     * @param int $page
     * @param int $size
     *
     * @return array
     */
    public function companyRolePaginate(int $userId, int $page, int $size): array
    {
        $query = CompanyJoinRoleRecord::query()
            ->with(['company', 'role:id,title'])
            ->where('company_id', $userId)
            ->orderByDesc('created_at');

        $total = $query->count();
        $list = $query->forPage($page, $size)->get()->toArray();

        return compact('total', 'list');
    }


    /**
     * @param int $companyId
     * @param int $roleId
     * @param int $expiredId
     * @return void
     */
    public function companyJoinRole(int $companyId, int $roleId, int $expiredId): void
    {
        // 店铺角色

        //具体店铺所选期限
        $expired = Expiredables::query()->where('id', $expiredId)->firstOrFail();
        // 当前用户是免费会员

        DB::transaction(function () use ($companyId,$roleId,$expired) {
            $now = Carbon::now();
            $expiredAt = (clone $now)->addDays($expired['expired_days']);
            // 创建购买记录
            CompanyJoinRoleRecord::create([
                'company_id' => $companyId,
                'role_id' => $roleId,
                'charge' => $expired['charge'],
                'started_at' => $now,
                'expired_at' => $expiredAt,
                'remark'=>'新增会员',
            ]);

            $this->companySerivice->changeRole($companyId, $roleId, $expiredAt->toString());
        });
    }

    /**
     * 店铺续期
     * @param int $companyId
     * @param array $product
     * @return void
     */
    public function companyContinueRole(int $companyId, array $company, int $roleId, int $expiredId): void
    {

        //具体店铺所选期限
        $expired = Expiredables::query()->where('id',$expiredId)->firstOrFail();
        DB::transaction(function () use ($companyId,$company,$roleId,$expired) {
            $startAt = Carbon::parse($company['expired_at']);
            $startAt = $startAt->gt(Carbon::now()) ? $startAt : Carbon::now();
            $expiredAt = (clone $startAt)->addDays($expired['expired_days']);
            // 创建购买记录
            CompanyJoinRoleRecord::create([
                'company_id' => $companyId,
                'role_id' =>$roleId,
                'charge' => $expired['charge'],
                'started_at' => $startAt,
                'expired_at' => $expiredAt,
                'remark'=>'续费会员',
            ]);
            // 修改user表
            $this->companySerivice->changeRole($companyId, $roleId,$expiredAt->toString());
        });
    }

    /**
     * 店铺续期
     * @param int $companyId
     * @param array $product
     * @return void
     */
    public function companyUpdateRole(int $companyId, array $company, int $roleId, float $charge , int $expiredDays): void
    {

        DB::transaction(function () use ($companyId,$company,$roleId,$charge,$expiredDays) {
            $startAt = Carbon::parse($company['expired_at']);
            $startAt = $startAt->gt(Carbon::now()) ? $startAt : Carbon::now();
            $expiredAt = (clone $startAt)->addDays($expiredDays);
            // 创建购买记录
            CompanyJoinRoleRecord::create([
                'company_id' => $companyId,
                'role_id' =>$roleId,
                'charge' => $charge,
                'started_at' => $startAt,
                'expired_at' => $expiredAt,
                'remark'=>'编辑会员',
            ]);
            // 修改user表
            $this->companySerivice->changeRole($companyId, $roleId,$expiredAt->toString());
        });
    }




    /**
     * 取消取限
     * @param int $companyId
     * @param int $roleId
     * @return void
     */
    public function companyDeleteRole(int $companyId, int $roleId): void
    {
        DB::transaction(function () use ($companyId,$roleId) {
            $expiredAt =  Carbon::now();
            // 创建购买记录
            CompanyJoinRoleRecord::create([
                'company_id' => $companyId,
                'role_id' =>$roleId,
                'charge' => 0,
                'started_at' => $expiredAt,
                'expired_at' => $expiredAt,
                'remark'=>'取消会员',
            ]);
            // 修改user表
            $this->companySerivice->changeRole($companyId, 0,$expiredAt->toString());
        });
    }



}
